/*
 * Copyright (c) 2016- 2020 qolome.com Inc. All Rights Reserved.
 * ProjectName: qolome-knowledge
 * FileName: QolomeClassLoader.java
 * Author: jiangfeng@qolome.com
 * Date: 2020/3/3 下午1:13
 * LastModified: 2020/03/03 12:46:03
 */

package com.qolome.knowledge.design.pattern.proxy.demo.proxy;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;

/**
 * @author Qolome
 * @version V1.0
 * @Description Qolome类加载器
 * @date 2020年 03月03日 12:43:00
 */
public class QolomeClassLoader extends ClassLoader{


    private File classPathFile;
    public  QolomeClassLoader(){
        String classPath = QolomeClassLoader.class.getResource("").getPath();
        this.classPathFile = new File(classPath);
    }


    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {

        String className = QolomeClassLoader.class.getPackage().getName()+"."+name;
        if(classPathFile  != null){
            File classFile = new File(classPathFile,name.replaceAll("\\.","/") + ".class");
            if(classFile.exists()){
                FileInputStream in = null;
                ByteArrayOutputStream out = null;
                try{
                    in = new FileInputStream(classFile);
                    out = new ByteArrayOutputStream();
                    byte [] buff = new byte[4096];
                    int len;
                    while ((len = in.read(buff)) != -1){
                        out.write(buff,0,len);
                    }
                    return defineClass(className,out.toByteArray(),0,out.size());
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
        return null;
    }
}
